package com.woniu.customer.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.customer.entity.Customer;
import com.woniu.customer.entity.CustomerOrder;
import com.woniu.customer.entity.GoodOrder;
import com.woniu.customer.entity.Goods;
import com.woniu.customer.entity.vo.InvestmentVO;
import com.woniu.customer.mapper.CustomerGoodOrderMapper;
import com.woniu.customer.mapper.CustomerMapper;
import com.woniu.customer.mapper.CustomerOrderMapper;
import com.woniu.customer.service.CustomerService;
import com.woniu.finance.entity.Tender;
import com.woniu.finance.mapper.TenderMapper;
import com.woniu.redisson.DistributedRedisLock;
import com.woniu.util.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TenderMapper tenderMapper;
    @Autowired(required = false)
    private CustomerOrderMapper customerOrderMapper;
    @Autowired(required = false)
    private CustomerGoodOrderMapper customerGoodOrderMapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public HttpResult<?> login(Customer customer) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", customer.getPhone()).eq("password", customer.getPassword());
        Customer c = customerMapper.selectOne(queryWrapper);
        if (c != null) {
            return new HttpResult<>().ok(c);
        } else {
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> register(Customer customer) {
        try {
            customerMapper.insert(customer);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findCustomerByPhone(String phone) {
        try {
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            Customer customer = customerMapper.selectOne(queryWrapper);
            return new HttpResult<>().ok(customer);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> updateCustomerinformation(Customer customer) {
        try {
            customerMapper.updateCustomerinformation(customer);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> CustomerInvest(InvestmentVO investment) {
        //设置密钥名
        String key = "cInvestLock";
        try {
            //设置锁
            DistributedRedisLock.acquire(key);
            //查询投资标的
            Tender tender = tenderMapper.selectById(investment.getTenderId());
            //查询用户信息
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", investment.getCustomerPhone());
            Customer customer = customerMapper.selectOne(queryWrapper);
            //比较投资金额与账户金额
            if (investment.getInvestmentNum().compareTo(customer.getAccountBalance()) < 1) {
                //判断标的金额剩余待融资金额与投资金融相比
                if ((tender.getAllFinancingAmount().subtract(tender.getNowFinancingAmount())).compareTo(investment.getInvestmentNum()) > -1) {
                    //更新标的资金池
                    tender.setNowFinancingAmount(tender.getNowFinancingAmount().add(investment.getInvestmentNum()));
                    //扣除账户金额并加入个人冻结资金池
                    customer.setAccountBalance(customer.getAccountBalance().subtract(investment.getInvestmentNum()));
                    customer.setAccountFrozen(customer.getAccountFrozen().add(investment.getInvestmentNum()));
                    //生成投资记录
                    CustomerOrder order = new CustomerOrder();
                    order.setTenderId(investment.getTenderId());
                    order.setCustomerPhone(investment.getCustomerPhone());
                    order.setInvestmentAmount(investment.getInvestmentNum());
                    order.setInvestmentTime(Timestamp.valueOf(sdf.format(new Date())));
                    order.setStatus(1);
                    //写入数据库
                    tenderMapper.updateById(tender);
                    customerMapper.updateById(customer);
                    customerOrderMapper.insert(order);
                    return new HttpResult<>().ok();
                } else {
                    return new HttpResult<>().fail();
                }
            } else {
                return new HttpResult<>().fail();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放
            DistributedRedisLock.release(key);
        }
        return new HttpResult<>().fail();
    }

    @Override
    public HttpResult<?> selectGoodList() {
        try {
            List<Goods> all = customerMapper.selectGoodList();
            return new HttpResult<>().ok(all);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> cutGoodGrade(String phone, Integer grade) {
        try {
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            Customer customer = customerMapper.selectOne(queryWrapper);
            customerMapper.cutGoodGrade(phone,customer.getGrade()-grade);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> addGoodOrder(GoodOrder goodOrder) {
        try {
            goodOrder.setBuyTime(Timestamp.valueOf(sdf.format(new Date())));
            customerGoodOrderMapper.insert(goodOrder);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> selectGoodOrderList(String phone) {
        try {
            QueryWrapper<GoodOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            List<GoodOrder> all = customerGoodOrderMapper.selectList(queryWrapper);
            return new HttpResult<>().ok(all);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }
}
